import { Button, Form, Input, message } from 'antd';
import { useEffect } from 'react';
import request from 'umi-request';
import { history } from 'umi';

// JSEncrypt用于做公钥的加密的
import JSEncrypt from 'jsencrypt';

const Index = () => {
  // 非对称加密
  // 1. 预登录
  // 预登录会接收到publicKey，就是公钥
  // 存储公钥,一般存在本地存储中
  useEffect(() => {
    request.get('http://www.pudge.wang:3333/api/users/key').then((res) => {
      console.log(res);
      localStorage.setItem('publicKey', res.publicKey);
    });
  }, []);

  const onFinish = (values: any) => {
    const publicKey = localStorage.getItem('publicKey');
    if (publicKey) {
      // 拿到加密实例
      const encrypt = new JSEncrypt();
      // 将公钥当作参数传入
      encrypt.setPublicKey(publicKey);
      // encrypt.encrypt用于得到密文, 里面只能传入字符串
      // info就是通过用户名和密码得到的密文
      const info = encrypt.encrypt(JSON.stringify(values));

      // 真正的登录
      request
        .post('http://www.pudge.wang:3333/api/users/login', {
          data: {
            info: info,
          },
        })
        .then((res) => {
          if (res.status === 0) {
            message.success('登录成功');
            localStorage.setItem('username', values.username);
            localStorage.setItem('token', res.token);
            localStorage.setItem('auth', JSON.stringify(res.auth));
            history.push('/home/welcome');
          } else {
            message.error(res.msg);
          }
        });
    }
  };

  return (
    <div style={{ overflow: 'hidden' }}>
      <Form
        style={{ width: 500, margin: '100px auto 0' }}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        // 自动填充功能
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
